<?php
/**
 * 海外仓-一件代发 (库存)
 * (model)
 */
namespace App\Models\OverSeasBa;

use App\Models\Basics\SysPlat;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use Illuminate\Database\Eloquent\Model;

class DropshippingInventoryFnsku extends Model{

    protected $table = 'os_b_dropshipping_inventory_fnsku';

    protected $guarded = [];

    public function warehouse(){
        return $this->belongsTo(Warehouse::class, 'warehouse_id');
    }

    public function sku(){
        return $this->belongsTo(ProductSku::class, 'psku_id');
    }

    public function skuClassify(){
        return $this->hasOneThrough(
            ProductClassify::class,
            ProductSku::class,
            'id',//中间表
            'id',//目标表
            'psku_id',//当前模型
            'classify_id'//中间表
        );
    }

    public static function getInstant($warehouseId, $accountId, $fnSku){
        $instant = self::query()
            ->where('warehouse_id', $warehouseId)
            ->where('account_id', $accountId)
            ->where('fnsku', $fnSku)
            ->value('instant');
        return $instant ?: 0;
    }

    /**
     * 海外仓代发在库、在途（汇总）
     * @param array $warehouseIds
     * @param int $pSkuId
     * @param int $platId
     * @param int $accountId
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getInstantAndTransit($warehouseIds = [], $pSkuId = 0, $platId = 0, $accountId = 0){
        $query = self::query();
        $query->selectRaw('sum(IFNULL(instant,0)) as instant, sum(IFNULL(transit,0)) as transit, sum(IFNULL(reserve,0)) as reserve');
        if ($warehouseIds) $query->whereIn('warehouse_id', $warehouseIds);
        if ($pSkuId > 0) $query->where('psku_id',$pSkuId);
        if ($platId > 0) $query->where('plat_id',$platId);
        if ($accountId > 0) $query->where('account_id', $accountId);

        return $query->first();
    }

    /**
     * 正常入库-更新FNSKU库存
     * @param $warehouseId
     * @param $accountId
     * @param $fnSku
     * @param $pSkuId
     * @param $num
     * @param $platId
     */
    public static function _upInventoryBoxFnSku($warehouseId,$accountId,$fnSku,$pSkuId,$num,$platId){
        $inventory = self::query()
            ->where('plat_id',$platId)
            ->where('warehouse_id',$warehouseId)
            ->where('account_id',$accountId)
            ->where('fnsku',$fnSku)
            ->lockForUpdate()
            ->first();
        if(!$inventory){
            self::query()->create([
                'plat_id' => $platId,
                'warehouse_id' => $warehouseId,
                'account_id' => $accountId,
                'fnsku' => $fnSku,
                'psku_id' => $pSkuId,
                'instant' => $num,
            ]);
        }else{
            $inventory->instant += $num;
            $inventory->transit -= min($inventory->transit,$num);
            $inventory->save();
        }
    }


    /**
     * JP-海外仓(代发)在库 （rakuten自动发货）
     * @param array $warehouseId
     * @param int $pSkuId
     * @param int $platId
     * @param int $accountId
     * @return int|mixed
     */
    public static function getInstantMax($warehouseId = [], $pSkuId = 0, $platId = 0, $accountId = 0){
        $query = self::query();
        if ($warehouseId) $query->whereIn('warehouse_id', $warehouseId);
        if ($pSkuId > 0) $query->where('psku_id', $pSkuId);
        if ($platId > 0) $query->where('plat_id', $platId);
        if ($accountId > 0) $query->where('account_id', $accountId);

        $instant = $query->max('instant');
        return $instant ?: 0;
    }

    /**
     * JP-海外仓(代发)在库(模型)
     * @param array $warehouseId
     * @param int $pSkuId
     * @param int $platId
     * @param int $accountId
     * @param string $str
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getInstantMaxFind($warehouseId = [], $pSkuId = 0, $platId = 0, $accountId = 0, $str = 'instant'){
        $query = self::query();
        if ($warehouseId) $query->whereIn('warehouse_id', $warehouseId);
        if ($pSkuId > 0) $query->where('psku_id', $pSkuId);
        if ($platId > 0) $query->where('plat_id', $platId);
        if ($accountId > 0) $query->where('account_id', $accountId);

        $query->orderByDesc('instant');
        return $query->lockForUpdate()->first();
    }

    /**
     * JP-验证海外仓库存 (验证海外仓代发库存)
     * @param $rakutenOrder
     * @return bool
     */
    public static function _checkDropshippingInventoryFnsku($rakutenOrder){
        if (!$rakutenOrder) return false;

        $inventoryFlag = false;
        foreach ($rakutenOrder->rakuten_orders_items as $_k => $_v) {
            //$pskuId = ProductRakutenSku::getValueByCode($_v->platform_sku, 'psku_id');
            $pskuId = ProductSku::getValueByCode($_v->variant_id, 'id');
            if (!$pskuId){
                $inventoryFlag = false;
                break;
            }

            //库存不足,跳出循环,终止当前订单(整单)
            $dropshippingInstant = self::getInstantMax([],$pskuId,SysPlat::PLAT_RAKUTEN);
            if (intval($dropshippingInstant) < intval($_v->units)) {
                $inventoryFlag = false;
                break;
            }
            $inventoryFlag = true;
        }

        return $inventoryFlag;
    }

    /**
     * JP-更新海外仓库存 (扣减海外仓代发库存)
     * @param $rakutenOrder
     * @return bool
     */
    public static function _saveDropshippingInventoryFnsku($rakutenOrder){
        if (!$rakutenOrder) return false;

        $inventoryFlag = false;
        foreach ($rakutenOrder->rakuten_orders_items as $_k => $_v){
            //$pskuId = ProductRakutenSku::getValueByCode($_v->platform_sku, 'psku_id');
            $pskuId = ProductSku::getValueByCode($_v->variant_id, 'id');
            if (!$pskuId){
                $inventoryFlag = false;
                break;
            }

            //海外仓(代发)库存
            $dropshippingInventory = self::getInstantMaxFind([],$pskuId,SysPlat::PLAT_RAKUTEN);
            if (!$dropshippingInventory){
                $inventoryFlag = false;
                break;
            }
            if (intval($dropshippingInventory->instant) < intval($_v->units)){
                $inventoryFlag = false;
                break;
            }
            $dropshippingInventory->instant -= intval($_v->units); //扣减在库
            $flag = $dropshippingInventory->save();
            if (!$flag){
                $inventoryFlag = false;
                break;
            }

            $inventoryFlag = true;
        }

        return $inventoryFlag;
    }

}
